import { defineEventHandler, readBody } from "h3";
import { emailService } from "../../utils/emailService";

export default defineEventHandler(async (event) => {
  try {
    const body = await readBody(event);
    const { email, type = 'verification' } = body;

    // 数据验证
    if (!email) {
      return {
        success: false,
        error: "邮箱地址不能为空",
      };
    }

    // 验证邮箱格式
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      return {
        success: false,
        error: "邮箱格式不正确",
      };
    }

    // 测试邮件服务连接
    const connectionTest = await emailService.verifyConnection();
    if (!connectionTest) {
      return {
        success: false,
        error: "邮件服务连接失败，请检查配置",
      };
    }

    let result;

    if (type === 'verification') {
      // 发送测试验证码邮件
      const testCode = '123456';
      result = await emailService.sendVerificationCode(email, testCode);
    } else if (type === 'welcome') {
      // 发送测试欢迎邮件
      result = await emailService.sendRegistrationSuccess(email, 'TestUser');
    } else {
      return {
        success: false,
        error: "不支持的邮件类型",
      };
    }

    if (result.success) {
      return {
        success: true,
        message: `测试邮件发送成功！请检查 ${email} 邮箱`,
        type,
        ...(type === 'verification' && { testCode: '123456' })
      };
    } else {
      return {
        success: false,
        error: result.error || "邮件发送失败",
      };
    }
  } catch (error) {
    console.error('测试邮件发送错误:', error);
    return {
      success: false,
      error: error instanceof Error ? error.message : "测试邮件发送失败",
    };
  }
});
